package com.security.controller;

import com.fasterxml.jackson.databind.json.JsonMapper;
import com.security.encryption.RSASignUtils;
import com.security.entity.AppInfo;
import com.security.service.AppInfoIService;
import com.security.tools.ObjectUtils;
import com.security.tools.RestTemplateUtil;
import com.security.vo.RestfulDTO;
import com.security.vo.UserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;

/**
 * Package: com.security.controller
 * Description：受保护的接口
 * Author: huangjian
 * Date:  2020/9/16 14:05
 * Modified By:
 * @author huangjian
 */
@RequestMapping("/gateway")
@Controller
@Slf4j
public class GatewayController {
    @Resource
    private AppInfoIService appInfoIService;
    private static JsonMapper jsonMapper=new JsonMapper();
    @GetMapping("/register")
    public String register(ModelMap modelMap){
        modelMap.put("appId","20200916144009");
        return "register";
    }
    @PostMapping("/add.do")
    public String add(UserDto userDto,String appId, ModelMap modelMap){
        AppInfo oneByAppId = appInfoIService.getOneByAppId(appId);
        log.info(oneByAppId.toString());
        userDto.setUid(System.currentTimeMillis());
        modelMap.put("userDto",userDto);

        try {
           new Thread(new Runnable() {
               @Override
               public void run() {
                  try {
                      String sourceSignData = RSASignUtils.getSourceSignData(ObjectUtils.objToMap(userDto));
                      log.info(sourceSignData);
                      String sign = RSASignUtils.signByPrivateKey(sourceSignData.getBytes(), oneByAppId.getPrivateKey());
                      RestfulDTO restfulDTO = RestfulDTO.success(userDto);
                      restfulDTO.setSign(sign);
                      String json = jsonMapper.writeValueAsString(restfulDTO);
                      String postResult = RestTemplateUtil.post(oneByAppId.getNotifyUrl(), json, null);
                      log.info("通知完成，返回信息"+postResult);
                  }catch (Exception e){
                      e.printStackTrace();
                  }
               }
           }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }

}
